import {
  CommentOutlined,
  LockOutlined,
  NotificationOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {Button, Form, Input, message, Popover, Progress } from 'antd';
import React, {useState} from 'react';
import ProForm, { ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { useIntl, Link, history, FormattedMessage, SelectLang, useModel } from 'umi';
import { show } from '@/utils/NotificationUtil';
import styles from './index.less';
import {formatMessage} from "@@/plugin-locale/localeExports";
import {login, getCurrentUser, recordIp, saveUser, register} from "@/pages/user/Login/service";
import {DefaultFooter} from "@ant-design/pro-layout";
import {MenuDataItem} from "@umijs/route-utils";
import {init} from "@/utils/WebSocketUtil";

const FormItem = Form.Item;
const InputGroup = Input.Group;
const passwordStatusMap = {
  ok: (
    <div className={styles.success}>
      <FormattedMessage id="register.strength.strong" />
    </div>
  ),
  pass: (
    <div className={styles.warning}>
      <FormattedMessage id="register.strength.medium" />
    </div>
  ),
  poor: (
    <div className={styles.error}>
      <FormattedMessage id="register.strength.short" />
    </div>
  ),
};
const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

/** 此方法会跳转到 redirect 参数所在的位置 */
const goto = () => {
  if (!history) return;
  setTimeout(() => {
    const { query } = history.location;
    const { redirect } = query as { redirect: string };
    history.push(redirect || '/');
  }, 100);
};

const Login: React.FC = () => {
  const [submitting, setSubmitting] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();
  const [reg, setReg] = useState<boolean>(true);
  const [visible, setvisible] = useState(false);
  const [popover, setpopover] = useState(false);
  const [form] = Form.useForm();
  const confirmDirty = false;

  const MyIcon = (item: MenuDataItem) => {
    return (
      <span className='anticon font'>
      <span className={`iconfont ${item.icon}`}></span>
    </span>
    )
  };

  const fixMenuItemIcon = (menus: MenuDataItem[]): MenuDataItem[] => {
    menus.forEach((item) => {
      const {icon, children} = item;
      if (typeof icon === 'string') {
        item.icon = <MyIcon icon={icon}/>;
      }
      children && children.length > 0 ? item.children = fixMenuItemIcon(children) : null
    });
    return menus
  };

  const handleSubmit = async (values: API.LoginParams) => {
    setSubmitting(true);
    try {
      login({...values}).then(res => {
        if (res.code == 200) {
          localStorage.setItem("token", res.data.token);
          recordIp();
          saveUser().then(s => {
            if (s.status == 200){
              getCurrentUser().then(e => {
                if (e.status == 200){
                  let user = e.data, messages = [], notifications = [];
                  window.permissions = user.permissionList.split(',');
                  window.top.user = user;
                  if (user.messageList){
                    user.messageList.split(',').map((msg: string) => {
                      if (msg){
                        const result = msg.split('-');
                        const type = result[0];
                        const link = result[1];
                        const content = result[2];
                        const time = result[3] + "-" + result[4] + "-" + result[5];
                        messages.push({
                          id: messages.length + 1,
                          avatar: <CommentOutlined style={{ color: 'orangered', cursor: 'pointer' }}/>,
                          title: content,
                          link: link,
                          datetime: time,
                          type: type,
                        })
                      }
                    })
                  }
                  if (user.notificationList){
                    user.notificationList.split(',').map((msg: string) => {
                      if (msg){
                        const result = msg.split('-');
                        const type = result[0];
                        const link = result[1];
                        const content = result[2];
                        const time = result[3] + "-" + result[4] + "-" + result[5];
                        notifications.push({
                          id: notifications.length + 1,
                          avatar: <NotificationOutlined style={{ color: 'skyblue', cursor: 'pointer' }}/>,
                          title: content,
                          link: link,
                          datetime: time,
                          type: type,
                        })
                      }
                    })
                  }
                  setInitialState({
                    ...initialState,
                    currentUser: {
                      ...user,
                      message: messages,
                      notification: notifications
                    },
                    menuData: fixMenuItemIcon(user.menuData)
                  });
                  //用户登录成功后建立websocket连接
                  init(user.loginName);
                  setSubmitting(false);
                  show('登录成功','欢迎回家', 'success');
                  goto();
                }
              })
            }
          })
        }else {
          setSubmitting(false);
        }
      })
    } catch (error) {
      setSubmitting(false);
      message.error('未知错误！');
    }
  };

  const toRegister = async () => {
    setReg(false);
  };

  const getPasswordStatus = () => {
    const value = form.getFieldValue('password');

    if (value && value.length > 9) {
      return 'ok';
    }

    if (value && value.length > 5) {
      return 'pass';
    }

    return 'poor';
  };

  const renderPasswordProgress = () => {
    const value = form.getFieldValue('password');
    const passwordStatus = getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  const onFinish = (values: any) => {
    register({...values}).then(res => {
      if (res.status == 1){
        message.success("注册成功!!!");
        setReg(true);
      }else if(res.status == 2){
        message.warning("用户名已被注册!");
      }else if(res.status == 4){
        message.error("用户名长度超出范围！");
      }else {
        message.error("注册失败!!!");
      }
    })
  };

  const checkPassword = (_: any, value: string | any[]) => {
    const promise = Promise; // 没有值的情况

    if (!value) {
      setvisible(!!value);
      return promise.reject(
        formatMessage({
          id: 'register.password.required',
        }),
      );
    } // 有值的情况

    if (!visible) {
      setvisible(!!value);
    }

    setpopover(!popover);

    if (value.length < 6) {
      return promise.reject('');
    }

    if (value && confirmDirty) {
      form.validateFields(['confirm']);
    }

    return promise.resolve();
  };

  const checkConfirm = (_: any, value: any) => {
    const promise = Promise;

    if (value && value !== form.getFieldValue('password')) {
      return promise.reject(
        formatMessage({
          id: 'register.password.twice',
        }),
      );
    }

    return promise.resolve();
  };

  const police = require('@/../public/policeLogo.png');

  return (
    <div className={styles.container} id='loginMain'>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/">
              <img alt="logo" className={styles.logo} src="/logoko.png" />
              <span className={styles.title}>JokerPan’s Home</span>
            </Link>
          </div>
        </div>

        <div className={styles.main}>
          {!reg && <>
            <div style={{height: '50px'}}></div>
            <Form form={form} name="UserRegister" onFinish={onFinish}>
              <FormItem
                name="loginName"
                rules={[
                  {
                    required: true,
                    message: formatMessage({
                      id: 'register.loginName.required',
                    }),
                  }
                ]}
              >
                <Input
                  size="large"
                  placeholder='请输入用户名'
                  allowClear={true}
                  maxLength={10}
                  showCount={true}
                />
              </FormItem>
              <FormItem
                name="email"
                rules={[
                  {
                    required: true,
                    message: formatMessage({
                      id: 'register.email.required',
                    }),
                  },
                  {
                    type: 'email',
                    message: formatMessage({
                      id: 'register.email.wrong-format',
                    }),
                  },
                ]}
              >
                <Input
                  size="large"
                  allowClear={true}
                  placeholder={formatMessage({
                    id: 'register.email.placeholder',
                  })}
                />
              </FormItem>
              <Popover
                getPopupContainer={(node) => {
                  if (node && node.parentNode) {
                    return node.parentNode;
                  }

                  return node;
                }}
                content={
                  visible && (
                    <div
                      style={{
                        padding: '4px 0',
                      }}
                    >
                      {passwordStatusMap[getPasswordStatus()]}
                      {renderPasswordProgress()}
                      <div
                        style={{
                          marginTop: 10,
                        }}
                      >
                        <FormattedMessage id="register.strength.msg" />
                      </div>
                    </div>
                  )
                }
                overlayStyle={{
                  width: 240,
                }}
                placement="right"
                visible={visible}
              >
                <FormItem
                  name="password"
                  className={
                    form.getFieldValue('password') &&
                    form.getFieldValue('password').length > 0 &&
                    styles.password
                  }
                  rules={[
                    {
                      validator: checkPassword,
                    },
                  ]}
                >
                  <Input
                    size="large"
                    type="password"
                    placeholder={formatMessage({
                      id: 'register.password.placeholder',
                    })}
                  />
                </FormItem>
              </Popover>
              <FormItem
                name="confirm"
                rules={[
                  {
                    required: true,
                    message: formatMessage({
                      id: 'register.confirm-password.required',
                    }),
                  },
                  {
                    validator: checkConfirm,
                  },
                ]}
              >
                <Input
                  size="large"
                  type="password"
                  placeholder={formatMessage({
                    id: 'register.confirm-password.placeholder',
                  })}
                />
              </FormItem>
              <InputGroup compact>
                <FormItem
                  style={{
                    width: '100%',
                  }}
                  name="phone"
                  rules={[
                    {
                      required: true,
                      message: formatMessage({
                        id: 'register.phone-number.required',
                      }),
                    },
                    {
                      pattern: /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/,
                      message: formatMessage({
                        id: 'register.phone-number.wrong-format',
                      }),
                    },
                  ]}
                >
                  <Input
                    size="large"
                    placeholder={formatMessage({
                      id: 'register.phone-number.placeholder',
                    })}
                  />
                </FormItem>
              </InputGroup>
              <FormItem>
                <Button
                  size="large"
                  loading={submitting}
                  type="primary"
                  htmlType="submit"
                  style={{
                    width: '58%'
                  }}
                >
                  <FormattedMessage id="register.register.register" />
                </Button>
                <a style={{float:'right', marginTop: '7px'}} onClick={() => setReg(true)}>
                  <FormattedMessage id="register.register.sign-in" />
                </a>
              </FormItem>
            </Form>
          </>}
          {reg && <ProForm
            initialValues={{
              autoLogin: true,
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({
                  id: 'pages.login.submit',
                  defaultMessage: '登录',
                }),
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading: submitting,
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            onFinish={async (values) => {
              handleSubmit(values as API.LoginParams);
            }}
          >
            <div style={{height: '50px'}}></div>
            <>
              <ProFormText
                name="username"
                placeholder='请输入用户名'
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                placeholder='请输入密码'
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>
            <div
              style={{
                marginBottom: 24,
              }}
            >
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
              </ProFormCheckbox>
              <a
                onClick={toRegister}
                style={{
                  float: 'right',
                }}
              >
                注册账号
              </a>
            </div>
          </ProForm>}
        </div>
      </div>
      <DefaultFooter
        style={{ backgroundColor: "transparent" }}
        links={[
          { key: '', title: <span><img src={police}/>&nbsp;鄂公网安备 42068302000301号</span>,
            href: 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=42068302000301', blankTarget: true},
          { key: '', title: '鄂ICP备2022006469号', href: 'https://beian.miit.gov.cn/', blankTarget: true }
        ]}
        copyright='2022 jokerpan.xyz 版权所有'
      />
    </div>
  );
};

export default Login;
